package com.tegistuff.webos.run.debugger.commands;

import com.intellij.xdebugger.XDebugSession;
import com.palm.webos.tools.internal.debugger.AppDebugSession;
import com.tegistuff.webos.run.debugger.WebOSDebugProcess;
import com.tegistuff.webos.run.debugger.infrastructure.WebOSCommandSpooler;

/**
 * BaseWebOSCommand.java
 *
 * Base class for all debugger commands.
 * Meta commands directly derive from this class, while commands interacting with the V8
 * debugger itself derive from WebOSDebuggerCommand.
 *
 * Copyright (C) 2011-2012 Timo Tegtmeier.
 * All rights reserved.
 */
public abstract class BaseWebOSCommand {

    private BaseWebOSCommand myListener;
    private boolean myIsDone;

    protected XDebugSession ourDebugSession;
    protected AppDebugSession ourAppDebugSession;
    protected WebOSDebugProcess ourDebugProcess;
    protected WebOSCommandSpooler ourCommandSpooler;

    public BaseWebOSCommand() {
    }

    public final void setSpooler(WebOSCommandSpooler spooler) {
        ourCommandSpooler = spooler;
        ourDebugProcess = spooler.getDebugProcess();
        ourDebugSession = ourDebugProcess.getSession();
        ourAppDebugSession = ourCommandSpooler.getAppDebugSession();
    }

    public final void setListener(BaseWebOSCommand listener) {
        myListener = listener;
    }

    protected final void notifyListener() {
        if(myListener != null){
            try {
                myListener.commandFinished(this);
            } catch (Exception e) {
                ourDebugSession.reportError("Error finishing debug command.");
            }
        }
    }
    
    protected synchronized final void done(boolean autoNotify) {
        myIsDone = true;
        if(autoNotify)
            notifyListener();
        ourCommandSpooler.done(this);
    }

    protected final void done() {
        done(true);
    }

    public final void waitForCompletion() throws InterruptedException {
        synchronized(this) {
            while(!myIsDone)
                wait();
        }
    }

    protected void commandFinished(BaseWebOSCommand command) throws Exception {}

    public abstract void execute() throws Exception;
}
